#include "writer.h"

#include "fragment.h"

#include <gio/gio.h>
#include <stdio.h>

#define DEBUG 1

gboolean
write_file (GList * blocks, gchar * path, gboolean write_crc)
{
	FILE_FRAGMENT *       file_fragment             = NULL;
	FILE_FRAGMENT_GROUP * file_fragment_group       = NULL;
	GFile *               file                      = NULL;
	GOutputStream *       output_stream             = NULL;
	GError *              error                     = NULL;
	guint                 number_of_fragments       = 0;
	guint                 number_of_fragment_groups = 0;
	guint                 iterator                  = 0;
	guint                 iterator_group            = 0;
	gboolean              successful                = TRUE;   

	file = g_file_new_for_path (path);

	if (!file)
	{
		g_printf ("\nNão foi possivel abrir o arquivo para escrita\n");

		successful = FALSE;
	}
	else
	{
		output_stream = G_OUTPUT_STREAM (g_file_create (file, G_FILE_CREATE_NONE, NULL, &error));

		if (error)
		{
			g_printf ("%s", error->message);
			g_error_free (error);
	        
			successful = FALSE;
		}
		else
		{
			number_of_fragment_groups = g_list_length (blocks);

			for (iterator_group = 0; iterator_group < number_of_fragment_groups; iterator_group++)
			{
				file_fragment_group = (FILE_FRAGMENT_GROUP *) g_list_nth_data (blocks, 0);

				number_of_fragments = g_list_length (file_fragment_group->data_list);

				for (iterator = 0; iterator < number_of_fragments; iterator++)
				{
					file_fragment = (FILE_FRAGMENT *) g_list_nth_data (file_fragment_group->data_list, 0);

					g_output_stream_write (G_OUTPUT_STREAM (output_stream),
								file_fragment->data,
								FRAGMENT_SIZE,
								NULL,
								&error);
						
					if (write_crc)
					{
						g_output_stream_write (G_OUTPUT_STREAM (output_stream),
									&(file_fragment->crc16),
									2,
									NULL,
									&error);
					}

					file_fragment_group->data_list = g_list_remove (file_fragment_group->data_list, file_fragment);

					if (error)
					{
						g_printf ("%s", error->message);		
						g_error_free (error);
                                        
						successful = FALSE;
					}
				} 

				blocks = g_list_remove (blocks, file_fragment_group);
			}	

			g_output_stream_close (output_stream, NULL, &error);

			if (error)
			{
				g_printf ("%s", error->message);
				g_error_free (error);
                        
			 	successful = FALSE;
			}
		}
	}

	return successful;
}
